package com.softeem.mpdemo.controller;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.mpdemo.dto.Result;
import com.softeem.mpdemo.entity.User;
import com.softeem.mpdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/user/login")
    public Result login(User user) {
        return userService.login(user);
    }

    @RequestMapping("/user/reg")
    public Result reg(User user) {
        return userService.reg(user);
    }

    @RequestMapping("/user/update")
    public Result modify(User user){
        if(Objects.nonNull(user.getPassword())){
            String salt = RandomUtil.randomString(6);
            String pwd = SecureUtil.md5(salt + user.getPassword());
            user.setPassword(pwd);
            user.setSalt(salt);
        }

        if(userService.updateById(user)){
            return Result.ok().setMsg("修改成功").setData(user);
        }
        return Result.fail().setMsg("更新失败");
    }

    @RequestMapping("user/listAll")
    public Result list(){
        List<User> list = userService.list();
        if(list.isEmpty()){
            return Result.fail().setMsg("无记录");
        }
        list.forEach(user -> {
            user.setPassword(DesensitizedUtil.password(user.getPassword()));
            user.setSalt(DesensitizedUtil.password(user.getSalt()));
        });
        return Result.ok().setMsg("查询成功").setData(list);
    }

    @RequestMapping("user/list")
    public Result list(Integer page,Integer limit){
        List<User> list = userService.list(new Page<>(page,limit));
        if(list.isEmpty()){
            return Result.fail().setMsg("无记录");
        }
        list.forEach(user -> {
            user.setPassword(DesensitizedUtil.password(user.getPassword()));
            user.setSalt(DesensitizedUtil.password(user.getSalt()));
        });
        return Result.ok().setMsg("查询成功").setData(list);
    }

    @RequestMapping("user/del")
    public Result delById(Integer id){
        User user = userService.getById(id);
        if(Objects.isNull(user)){
            return Result.fail().setMsg("该管理员不存在或者已经被删除!");
        }
        if(userService.removeById(id)){
            return Result.ok().setMsg("删除成功").setData(user);
        }
        return Result.fail().setMsg("删除失败");
    }

}